<template>
  <div>
    <!-- <div class="operation-btn">
      <div class="dis-flex flex-x-end ">

      </div>
    </div> -->
    <el-table ref="table" class="table" :data="detailsList.data" style="width: 100%" size="small" row-key="id" :span-method="objectSpanMethod">
      <el-table-column type="selection" min-width="20" />
      <el-table-column label="供应商" prop="supplier_name" min-width="60" fixed />
      <el-table-column label="子采购单单号" prop="purchase_id" min-width="100" fixed />
      <el-table-column label="图片" min-width="60">
        <template slot-scope="scope">
          <img v-viewer :src="scope.row.imgurl" width="40">
        </template>
      </el-table-column>
      <el-table-column label="产品类别/单位" min-width="100">
        <template slot-scope="scope">
          {{ scope.row.sort_name }} / {{ scope.row.use_unit }}
        </template>
      </el-table-column>
      <el-table-column label="产品名称" min-width="250" prop="name" />
      <el-table-column label="颜色" min-width="100" prop="color_name" />
      <el-table-column label="规格" min-width="60" prop="spec_value" />
      <el-table-column label="采购数" min-width="60" prop="in_num">
        <template slot="header">
          <label class="col-blue">采购数</label>
        </template>
      </el-table-column>
      <el-table-column label="预计到货时间" min-width="150" prop="receive_time">
        <template slot="header">
          <label class="col-blue">预计到货时间</label>
        </template>
        <template slot-scope="scope">
          <el-date-picker v-if="purchase_id === scope.row.purchase_id" v-model="scope.row.receive_time" size="mini" value-format="yyyy-MM-dd" type="date" placeholder="选择日期" />
          <label v-else>{{ scope.row.receive_time }}</label>
        </template>
      </el-table-column>
      <el-table-column label="入库数" min-width="60" prop="in_stock" />
      <el-table-column label="待入库数" min-width="80" prop="out_stock" />
      <el-table-column label="差异数" min-width="60" prop="difference_num">
        <template slot-scope="scope">
          <div class="dis-flex">
            <div v-if="scope.row.difference_num > 0" class="row_div_difference success_row">超</div>
            <div v-if="scope.row.difference_num < 0" class="row_div_difference danger_row">缺</div>
            <label> {{ scope.row.difference_num }}</label>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="总可用数" min-width="80" prop="stock_actual" />
      <el-table-column label="上次含税单价" min-width="100" prop="last_price" />
      <el-table-column label="单价" min-width="80" prop="price">
        <template slot-scope="scope">
          <el-input v-if="purchase_id === scope.row.purchase_id" v-model="scope.row.price" size="mini" />
          <label v-else>{{ scope.row.price }}</label>
        </template>
      </el-table-column>
      <el-table-column label="总金额(元)" min-width="80" prop="total_price" />
      <el-table-column label="标准集装箱数量" min-width="110" prop="box_contain_num">
        <template slot-scope="scope">
          <el-input v-if="purchase_id === scope.row.purchase_id" v-model="scope.row.box_contain_num" size="mini" />
          <label v-else>{{ scope.row.box_contain_num }}</label>
        </template>
      </el-table-column>
      <el-table-column label="箱数" min-width="80" prop="box_num">
        <template slot-scope="scope">
          <el-input v-if="purchase_id === scope.row.purchase_id" v-model="scope.row.box_num" size="mini" />
          <label v-else>{{ scope.row.box_num }}</label>
        </template>
      </el-table-column>
      <el-table-column label="装箱编码" min-width="80" prop="box_num">
        <template slot-scope="scope">
          <el-input v-if="purchase_id === scope.row.purchase_id" v-model="scope.row.box_num" size="mini" />
          <label v-else>{{ scope.row.box_num }}</label>
        </template>
      </el-table-column>
      <el-table-column label="采购员" min-width="150" prop="purchase_user">
        <template slot-scope="scope">
          <el-select v-if="purchase_id === scope.row.purchase_id" v-model="scope.row.purchase_user_id" placeholder="采购员" filterable size="small">
            <el-option :value="0" label="请选择采购员" />
            <el-option v-for="(item, index) in adminList" :key="index" :value="item.id" :label="item.real_name" />
          </el-select>
          <label v-else>{{ scope.row.purchase_user }}</label>
        </template>
      </el-table-column>
      <el-table-column label="税率(%)" min-width="80" prop="taxrate">
        <template slot-scope="scope">
          <el-input v-if="purchase_id === scope.row.purchase_id" v-model="scope.row.taxrate" size="mini" />
          <label v-else>{{ scope.row.taxrate }}</label>
        </template>
      </el-table-column>
      <el-table-column label="预付金" min-width="80" prop="payment_type">
        <template slot-scope="scope">
          <el-input v-if="purchase_id === scope.row.purchase_id" v-model="scope.row.payment_type" size="mini" />
          <label v-else>{{ scope.row.payment_type }}</label>
        </template>
      </el-table-column>
      <el-table-column label="采购状态" width="80" prop="status">
        <template slot-scope="scope">
          <div v-if="scope.row.status == 0" class="row_div primary_row">未收货</div>
          <div v-if="scope.row.status == 1" class="row_div success_row">已入库</div>
          <div v-if="scope.row.status == 2" class="row_div success_row">部分入库</div>
          <div v-if="scope.row.status == 3" class="row_div success_row">已收货</div>
          <div v-if="scope.row.status == 4" class="row_div success_row">已质检</div>
        </template>
      </el-table-column>
      <el-table-column key="id" label="采购合同" min-width="130" prop="contract_url">
        <template slot-scope="scope">
          <div v-if="purchase_id === scope.row.purchase_id && !scope.row.contract_url">
            <el-button :id="'selectFileId'+scope.row.id" size="mini"> <svg-icon icon-class="upload" />上传文件</el-button>
          </div>
          <div v-if="scope.row.contract_url">
            <a :href="scope.row.contract_url" target="_blank">
              <el-link type="primary" :underline="false"><svg-icon icon-class="see" /> 查看</el-link>
            </a>
            <el-link type="danger" :underline="false" @click="delUrl(scope.row)">删除</el-link>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="收货地址" min-width="150" prop="address">
        <template slot-scope="scope">
          <el-input v-if="purchase_id === scope.row.purchase_id" v-model="scope.row.address" size="mini" />
          <label v-else>{{ scope.row.address }}</label>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="150" prop="operation" fixed="right">
        <template slot-scope="scope">
          <el-link type="primary" :underline="false" @click="set_upload_param(scope.row)">编辑</el-link>
          <el-link type="primary" :underline="false" @click="save(scope.row)">提交</el-link>
        </template>
      </el-table-column>
    </el-table>
    <Pagination ref="paginationOne" :total.sync="detailsList.total" :current-page.sync="currentPage" @handleCurrentChange="show(purchase_unify_id)" />
  </div>
</template>
<script>
/*
不使用上传组件原因：
由于table的fixed属性导致组件会重复渲染
后果：选择文件时会重复弹出选择文件夹弹框
*/
import plupload from 'plupload'
import { Upload } from '@/api/upload'
import { PurchaseDetail } from '@/api/purchase/purchaseDetail'
import Pagination from '@/components/Pagination'
export default {
  name: 'PurchaseDetail',
  components: {
    Pagination
  },
  props: {
    adminList: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      detailsList: {
        data: []
      },
      currentPage: 1,
      purchase_unify_id: '',
      purchase_id: '',
      spanArr: [], // 一个空的数组，用于存放每一行记录的合并数
      pos: 0, // spanArr 的索引
      contentSpanArr: [],
      position: 0,
      new_multipart_params: {},
      host: ''
    }
  },
  created() {
    // this.show(4)
  },
  methods: {
    show(purchase_unify_id, seach = {}) {
      this.purchase_unify_id = purchase_unify_id
      PurchaseDetail.pagePurchaseDetail({ ...{ purchase_unify_id, page: this.currentPage }, ...seach }).then((res) => {
        this.detailsList.data = res.data.data.map(item => ({ ...item, is_edit: false }))
        this.merge(this.detailsList.data)
      }).catch(() => {})
    },
    // 合并单元格
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (column.property === 'supplier_name') {
        const _row = this.spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      }
      if (column.property === 'purchase_id' || column.property === 'status' || column.property === 'contract_url' ||
       column.property === 'address' || column.property === 'taxrate' || column.property === 'operation' || column.property === 'payment_type') {
        const _row = this.contentSpanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      }
    },
    // 合并单元格
    merge(data) {
      this.spanArr = []
      this.contentSpanArr = []
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanArr.push(1)
          this.pos = 0
          this.contentSpanArr.push(1)
          this.position = 0
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i].supplier_id) { // 供应商
            if (data[i].supplier_id === data[i - 1].supplier_id) {
              this.spanArr[this.pos] += 1
              this.spanArr.push(0)
            } else {
              this.spanArr.push(1)
              this.pos = i
            }
          } else {
            this.spanArr.push(1)
            this.pos = i
          }
          if (data[i].purchase_id === data[i - 1].purchase_id) { // 子采购单
            this.contentSpanArr[this.position] += 1
            this.contentSpanArr.push(0)
          } else {
            this.contentSpanArr.push(1)
            this.position = i
          }
        }
      }
    },
    // 删除上传文件
    delUrl(val) {
      val.contract_url = ''
      this.set_upload_param(val)
    },
    // 保存
    save(val) {
      const filterItem = this.detailsList.data.filter(item => { return item.purchase_id === val.purchase_id })
      if (filterItem[0]) {
        const param = {
          purchase_id: filterItem[0].purchase_id,
          storage_sn: filterItem[0].storage_sn,
          taxrate: filterItem[0].purchase_id,
          address: filterItem[0].address,
          payment_type: filterItem[0].payment_type,
          contract_url: filterItem[0].contract_url,
          detail: []
        }
        filterItem.forEach(ele => {
          const obj = {
            id: ele.id,
            receive_time: ele.receive_time ? ele.receive_time : '',
            price: ele.price,
            box_contain_num: ele.box_contain_num,
            box_num: ele.box_num,
            box_code: ele.box_code,
            purchase_user_id: ele.purchase_user_id,
            purchase_user: this.adminList.find(x => x.id === ele.purchase_user_id) ? this.adminList.find(x => x.id === ele.purchase_user_id).real_name : ''
          }
          param.detail.push(obj)
        })
        PurchaseDetail.editPurchase(param).then((res) => {
          this.$message.success('保存成功')
          this.purchase_id = ''
          this.show(this.purchase_unify_id)
        }).catch(() => {})
      }
    },
    // 上传文件
    // 获取阿里云签名
    async send_request() {
      await Upload.getAliyunOssSignature({ dir: 'docx' }).then((res) => {
        const data = res.data
        this.host = data.host
        this.new_multipart_params = {
          key: data.dir,
          policy: data.policy,
          OSSAccessKeyId: data.accessid,
          success_action_status: '200', // 让服务端返回200,不然，默认会返回204
          callback: data.callback,
          signature: data.signature
        }
      }).catch(() => {})
    },
    // 向阿里云上传
    async set_upload_param(val) {
      this.purchase_id = val.purchase_id
      await this.send_request()
      this.initPlUploader(val)
    },
    // 获取文件后缀名
    get_suffix(filename) {
      const pos = filename.lastIndexOf('.')
      let suffix = ''
      if (pos !== -1) {
        suffix = filename.substring(pos)
      }
      return suffix
    },
    // 随机数
    random_string(len) {
      len = len || 32
      var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
      var maxPos = chars.length
      var pwd = ''
      for (var i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    },
    /*
     * 初始化上传插件
    */

    initPlUploader(val) {
      var _this = this
      var message = ''

      var uploader = new plupload.Uploader({
        runtimes: 'html5,flash,silverlight,html4', // 用来指定上传方式，指定多个上传方式请使用逗号隔开
        browse_button: 'selectFileId' + val.id, // 触发文件选择对话框的DOM元素，当点击该元素后便后弹出文件选择对话框。该值可以是DOM元素对象本身，也可以是该DOM元素的id
        multi_selection: true, // 是否可以在文件浏览对话框中选择多个文件
        flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf', // flash上传组件的url地址，如果是相对路径，则相对的是调用Plupload的html文档。当使用flash上传方式会用到该参数。
        silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap', // silverlight上传组件的url地址，如果是相对路径，则相对的是调用Plupload的html文档。当使用silverlight上传方式会用到该参数。
        url: 'http://oss.aliyuncs.com', // 服务器端接收和处理上传文件的脚本地址，可以是相对路径(相对于当前调用Plupload的文档)，也可以是绝对路径
        // required_features: 'send_binary_string',//可以使用该参数来设置你必须需要的一些功能特征，Plupload会根据你的设置来选择合适的上传方式。因为，不同的上传方式，支持的功能是不同的，比如拖拽上传只有html5上传方式支持，图片压缩则只有html5,flash,silverlight上传方式支持。该参数的值是一个混合类型，可以是一个以逗号分隔的字符串
        filters: {
          mime_types: [{
            title: 'txt',
            extensions: 'txt,doc,docx,ppt,pptx,xls,xlsx,pdf',
            mimeTypes: 'text/plain,application/msword,application/powerpoint,application/excel,application/pdf'
          }], // 允许上传哪些类型文件的集合
          max_file_size: '500mb', // 上传文件大小的限制
          prevent_duplicates: true // 不允许选取重复文件
        },
        init: {
          // 选择文件
          FilesAdded: function(up, files) {
            message = _this.$message({
              message: '上传中',
              duration: 0
            })
            plupload.each(files, function(file) { // 遍历文件
              const suffix = _this.get_suffix(file.name)
              _this.fileName = _this.random_string(10) + suffix
              file.target_name = _this.fileName
            })
            uploader.start()
          },
          BeforeUpload: function(up, file) {
            if (file) {
              _this.new_multipart_params.key = _this.new_multipart_params.key + file.target_name
              _this.$set(file, 'target_name', _this.new_multipart_params.key)
            }
            up.setOption({
              url: _this.host,
              multipart_params: _this.new_multipart_params
            })

            up.start()
          },

          UploadProgress: function(up, file) {},
          // 文件上传成功
          FileUploaded: function(up, file, info) {
            message.close()
            console.log(up, file, info, 'up, file, info')
            if (info.status === 200) {
              val.contract_url = _this.host + file.target_name
              // 成功后销毁该实例
              uploader.destroy()
            } else if (info.status === 203) {
              _this.$message.error(info.response)
            } else {
              _this.$message.error(info.response)
            }
          },

          Error: function(up, err) {
            message.close()
            if (err.code === -600) {
              _this.$message.error('选择的文件太大了')
            } else if (err.code === -601) {
              _this.$message.error('选择的文件后缀不对')
            } else if (err.code === -602) {
              _this.$message.error('这个文件已经上传过一遍了')
            } else {
              _this.$message.error(err.response)
            }
          }
        }
      })
      uploader.init()
    }
  }
}
</script>
<style lang="scss" scoped>
.operation-btn{
 position: absolute;
 right: 10px;
 top: 15px;
 background: white;
height: 40px;
z-index: 2;
 min-width: 80%;
}
.table{
  .row_div_difference{
  min-width: 0px;
  padding:0 3px;
  margin-right: 5px;
  }
  .el-date-editor{
    width: 100%;
  }
}

</style>
